import fs from 'fs';
import path from 'path';
import mammoth from 'mammoth';
import sharp from 'sharp';

// 获取当前文件目录（ES 模块方式）
const __dirname = path.dirname(new URL(import.meta.url).pathname);

// 输入和输出配置
const inputPath = path.join(__dirname, 'data', '绩效信息化知识库.docx');
const outputDir = path.join(__dirname, 'output-dir');
const outputHtmlPath = path.join(outputDir, 'output.html');
const outputContentPath = path.join(outputDir, 'content-only.html');

// 自定义样式映射
const styleMap = [
    "p[style-name='Title'] => h1",
    "p[style-name='Heading 1'] => h1",
    "p[style-name='Heading 2'] => h2",
    "p[style-name='Heading 3'] => h3",
    "p[style-name='Heading 4'] => h4",
    "p[style-name='Heading 5'] => h5",
    "p[style-name='Heading 6'] => h6"
];

// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
}

console.log('开始将DOCX转换为HTML，并将图片转为Base64...');

// 转换DOCX为HTML，将图片转为Base64内嵌
mammoth.convertToHtml({
    path: inputPath
}, {
    styleMap: styleMap,
    convertImage: mammoth.images.imgElement(async function (image) {
        const imageBuffer = await image.read();
        // 图片压缩配置
        const compressConfig = {
            maxWidth: 930,    // 最大宽度，超过将按比例缩小
            quality: 0.01,     // 质量参数（0-1之间）
            withMetadata: false // 移除元数据以减小大小
        };

        // 使用sharp压缩图片
        let compressedBuffer = imageBuffer;
        const originalSize = imageBuffer.length;

        // 只压缩较大的图片（大于10KB）
        if (originalSize > 10 * 1024) {
            try {
                // 根据图片类型选择合适的压缩方式
                if (image.contentType === 'image/png') {
                    // PNG使用0-100之间的quality值
                    compressedBuffer = await sharp(imageBuffer)
                        .resize(compressConfig.maxWidth)
                        .png({ quality: Math.round(compressConfig.quality * 100), force: true })
                        .toBuffer();
                } else if (image.contentType === 'image/jpeg' || image.contentType === 'image/jpg') {
                    // JPEG使用0-100之间的quality值
                    compressedBuffer = await sharp(imageBuffer)
                        .resize(compressConfig.maxWidth)
                        .jpeg({ quality: Math.round(compressConfig.quality * 100), progressive: true })
                        .toBuffer();
                } else {
                    // 对于其他类型，只调整大小
                    compressedBuffer = await sharp(imageBuffer)
                        .resize(compressConfig.maxWidth)
                        .toBuffer();
                }

                const compressedSize = compressedBuffer.length;
                const compressionRatio = ((originalSize - compressedSize) / originalSize * 100).toFixed(1);
                console.log(`已压缩图片: ${image.contentType}, 原始大小: ${(originalSize / 1024).toFixed(1)}KB, 压缩后: ${(compressedSize / 1024).toFixed(1)}KB, 减少: ${compressionRatio}%`);
            } catch (error) {
                console.error('图片压缩失败，使用原图:', error.message);
            }
        }

        // 将压缩后的图片转为Base64字符串
        const base64String = compressedBuffer.toString('base64');
        const contentType = image.contentType;
        const base64DataUri = `data:${contentType};base64,${base64String}`;

        console.log(`已将图片转为Base64: ${contentType}`);

        // 返回带有Base64数据URI的图片元素
        return { src: base64DataUri };
    })
})
    .then(result => {
        const htmlContent = result.value;
        const messages = result.messages;

        // 生成完整的HTML文件内容
        const fullHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>绩效信息化知识库</title>
    <style>
        /* 基础样式 */
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .content {
            background-color: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        /* 标题样式 */
        h1, h2, h3, h4, h5, h6 {
            color: #2c3e50;
            margin-top: 1.5em;
            margin-bottom: 0.8em;
        }
        h1 {
            font-size: 2.5em;
            border-bottom: 3px solid #3498db;
            padding-bottom: 0.3em;
        }
        h2 {
            font-size: 2em;
            border-bottom: 2px solid #3498db;
            padding-bottom: 0.3em;
        }
        /* 段落样式 */
        p {
            margin-bottom: 1em;
            text-align: justify;
        }
        /* 图片样式 */
        img {
            max-width: 100%;
            height: auto;
            display: block;
            margin: 20px auto;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            body {
                padding: 10px;
            }
            .content {
                padding: 20px;
            }
            h1 {
                font-size: 2em;
            }
            h2 {
                font-size: 1.5em;
            }
        }
    </style>
</head>
<body>
    <div class="content">
        ${htmlContent}
    </div>
</body>
</html>`;

        // 写入带HTML元素包裹的完整HTML文件
        fs.writeFileSync(outputHtmlPath, fullHtml);
        console.log(`带HTML元素包裹的文件已生成: ${outputHtmlPath}`);

        // 写入只有内容部分的文件（没有HTML、HEAD、BODY等标签）
        fs.writeFileSync(outputContentPath, htmlContent);
        console.log(`纯内容文件已生成: ${outputContentPath}`);

        // 按一级标题分割内容并生成多个文件
        const splitContentByH1 = (content) => {
            // 使用正则表达式匹配h1标签和内容
            const h1Regex = /<h1[^>]*>(.*?)<\/h1>/g;
            const sections = [];
            let currentSection = null;
            let lastIndex = 0;
            let match;

            // 查找所有h1标签
            while ((match = h1Regex.exec(content)) !== null) {
                const h1Content = match[1];
                const h1Start = match.index;
                const h1End = h1Regex.lastIndex;

                // 处理前一个section的内容（如果存在）
                if (currentSection && lastIndex < h1Start) {
                    currentSection.content = content.substring(lastIndex, h1Start).trim();
                    sections.push(currentSection);
                }

                // 创建新的section
                currentSection = {
                    title: h1Content,
                    content: '',
                    startIndex: h1Start
                };

                lastIndex = h1Start;
            }

            // 处理最后一个section
            if (currentSection && lastIndex < content.length) {
                currentSection.content = content.substring(lastIndex).trim();
                sections.push(currentSection);
            }

            return sections;
        };

        // 清理文件名，移除特殊字符
        const sanitizeFilename = (filename) => {
            return filename
                .replace(/[\\/:*?"<>|]/g, '_')  // 移除文件系统不允许的字符
                .replace(/\s+/g, '_')          // 将空格替换为下划线
                .substring(0, 100);           // 限制文件名长度
        };

        // 创建按h1分割的文件
        const sectionsDir = path.join(outputDir, 'sections');
        if (!fs.existsSync(sectionsDir)) {
            fs.mkdirSync(sectionsDir, { recursive: true });
        }

        const sections = splitContentByH1(htmlContent);
        if (sections.length > 0) {
            console.log(`已按一级标题分割为 ${sections.length} 个文件:`);
            sections.forEach((section, index) => {
                const filename = `${index + 1}_${sanitizeFilename(section.title)}.html`;
                const filePath = path.join(sectionsDir, filename);
                fs.writeFileSync(filePath, section.content);
                console.log(`- ${filename}: ${section.title}`);
            });
        } else {
            console.log('未找到一级标题，无法分割文件。');
        }

        // 输出转换过程中的消息
        if (messages.length > 0) {
            console.log('转换过程中的消息:');
            messages.forEach(message => {
                console.log(`- ${message}`);
            });
        }

        console.log('DOCX转HTML完成！已生成两个文件：带HTML元素包裹的文件和纯内容文件，所有图片已转为Base64内嵌。');
    })
    .catch(error => {
        console.error('转换过程中发生错误：', error);
    });